<template>
  <div class="list-pages white-bg">
    <div class="search-form-box">
      <a-form
        :model="queryState"
        name="horizontal_login"
        :label-col="labelCol"
        autocomplete="off"
        @finish="onFinish"
      >
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="教师姓名" name="keyword">
              <a-input
                v-model:value="queryState.name"
                placeholder="请输入教师姓名"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="实验室" name="customer_type_id">
              <a-select
                v-model:value="queryState.laboratory_idArray"
                placeholder="请选择实验室"
              >
                <a-select-option
                  v-for="(item, index) in laboratoryOptions"
                  :key="index"
                  :value="item.value"
                  >{{ item.text }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="预约状态" name="customer_status_id">
              <a-select
                v-model:value="queryState.appointment_status_idArray"
                placeholder="请选择预约状态"
              >
                <a-select-option
                  v-for="(item, index) in appointmentStatusOptions"
                  :key="index"
                  :value="item.value"
                  >{{ item.text }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="日期" name="customer_type_id">
              <a-range-picker
                :value="queryState.time"
                format="YYYY-MM-DD"
                @change="onChangeDate"
              />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6">
            <a-form-item>
              <div class="search-btn-box" :class="{ pt: expand }">
                <a-button
                  :icon="h(SearchOutlined)"
                  type="primary"
                  html-type="submit"
                  class="search-btn"
                  >查询</a-button
                >
                <a-button
                  :icon="h(ReloadOutlined)"
                  class="reset-btn"
                  @click="resetForm"
                  >重置</a-button
                >
                <a
                  class="expand-btn"
                  style="font-size: 12px; margin-left: 12px"
                  @click="expand = !expand"
                >
                  <template v-if="expand">
                    <UpOutlined />
                  </template>
                  <template v-else>
                    <DownOutlined />
                  </template>
                  {{ expand ? "收起查询" : "展开查询" }}
                </a>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="opt-button-box">
      <a-button type="primary" class="btn" @click="handleAdd">
        <img src="/icons/common/icon-add.png" class="icon" />创建预约</a-button
      >
    </div>
    <div class="table-wrapper" ref="tableRef">
      <a-table
        class="table-box"
        row-key="index"
        :columns="columns"
        :dataSource="tableData"
        :row-class-name="
          (_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        "
        sticky
        :scroll="{ y: true, x: 1100 }"
        :pagination="pagination"
        @change="onChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'begin_time'">
            {{ record.begin_time }} - {{ record.end_time }}
          </template>
          <template v-if="column.dataIndex == 'operation'">
            <!-- <a-button type="link" class="link" @click="handleDetail(record)">
              撤销
            </a-button> -->
            <a-popconfirm
              title="确定撤销预约吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelte(record)"
            >
              <a href="#">撤销</a>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal
      v-model:open="modal2Visible"
      title="实验室预约"
      centered
      @ok="handleOk"
    >
      <a-form
        ref="formRef"
        :model="formState"
        name="horizontal_login"
        layout="vertical"
        :label-col="{ style: { width: '300px' } }"
        autocomplete="off"
        :rules="rules"
      >
        <a-row :gutter="[16, 16]">
          <a-col :span="24">
            <a-form-item label="是否重复" name="repeat_type_id">
              <a-select
                v-model:value="formState.repeat_type_id"
                placeholder="请选择是否重复"
              >
                <a-select-option
                  v-for="(item, index) in appointmentRepeatTypeOptions"
                  :key="index"
                  :value="item.value"
                  >{{ item.text }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="生效日期" name="appointmentdate">
              <a-date-picker
                style="width: 100%"
                v-model:value="formState.appointmentdate"
                format="YYYY-MM-DD"
                @change="onChangeAppointmentFormDate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="起止时间" name="date">
              <!-- <a-range-picker style="width: 100%;" v-model:value="formState.date" format="YYYY-MM-DD"  @change="onChangeFormDate" /> -->
              <a-time-range-picker
                value-format="HH:mm"
                format="HH:mm"
                v-model:value="formState.date"
                @change="onChangeFormDate"
              />
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="智能跳过法定节假日" name="skip_holiday">
              <a-select
                v-model:value="formState.skip_holiday"
                placeholder="请选择是否智能跳过法定节假日"
              >
                <a-select-option :value="true">是</a-select-option>
                <a-select-option :value="false">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="实验室" name="laboratory_id">
              <a-select
                v-model:value="formState.laboratory_id"
                placeholder="请选择实验室"
              >
                <a-select-option
                  v-for="(item, index) in laboratoryOptions"
                  :key="index"
                  :value="item.value"
                  >{{ item.text }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="实验名称" name="experiment_name">
              <a-input
                v-model:value="formState.experiment_name"
                placeholder="请输入实验名称"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="授课教师" name="teacher_id">
              <a-select
                v-model:value="formState.teacher_id"
                placeholder="请选择授课教师"
              >
                <a-select-option
                  v-for="(item, index) in teacherOptions"
                  :key="index"
                  :value="item.teacher_id"
                  >{{ item.user.real_name }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>

          <!-- <a-col :span="24">
            <a-form-item label="起止时间" v-if="formState.repeat_type_id" name="time">
              <a-time-range-picker style="width: 100%;"  v-model:value="formState.time" format="HH:mm" placement="bottomLeft" @change="onChangeFormTime" />
            </a-form-item>
          </a-col> -->
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import api from "@/api";
import SAPI from "@/api/system";
import { useGlobalStore } from "@/store/modules/global";
import {
  DownOutlined,
  ReloadOutlined,
  SearchOutlined,
  UpOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { computed, h, nextTick, onMounted, onUnmounted, ref } from "vue";
import { useRouter } from "vue-router";

const store = useGlobalStore();
const router = useRouter();
const labelCol = { style: { width: "80px" } };

const rules = ref({
  laboratory_id: [
    {
      required: true,
      message: "请选择实验室",
      trigger: "blur",
    },
  ],
  teacher_id: [
    {
      required: true,
      message: "请选择授课教师",
      trigger: "blur",
    },
  ],
  experiment_name: [
    {
      required: true,
      message: "请输入实验室名称",
      trigger: "blur",
    },
  ],
  date: [
    {
      required: true,
      message: "请选择有效期限",
      trigger: "blur",
    },
  ],
  appointmentdate: [
    {
      required: true,
      message: "请选择预约日期",
      trigger: "blur",
    },
  ],
});

const queryState = ref({
  laboratory_id: "",
  teacher_id: undefined,
  is_repeat: undefined,
  begin_dateRange: undefined,
  time: [],
});
const resetForm = () => {
  queryState.value = {
    name: "",
    laboratory_idArray: undefined,
    appointment_status_idArray: undefined,
    begin_dateRange: undefined,
    time: [],
  };
  getApiAppointmentPagedListPost();
};

const formState = ref({
  laboratory_id: null,
  teacher_id: null,
  repeat_type_id: "",
  experiment_name: "",
  is_repeat: null,
  date: null,
  time: null,
  skip_holiday: null,
  appointmentdate: null,
});

const windowWidth = ref(window.innerWidth);
const expand = ref(true);

//获取实验室
const laboratoryOptions = ref([]);
const getApiLaboratoryOptionsPost = async () => {
  const res = await api.apiLaboratoryOptionsPost({ keyWords: "" });
  console.log(res);
  laboratoryOptions.value = res.data || [];
};

//获取预约分类
const appointmentStatusOptions = ref([]);
const getApiAppointmentStatusOptionsPost = async () => {
  const res = await api.apiAppointmentStatusOptionsPost({ keyWords: "" });
  console.log(res);
  appointmentStatusOptions.value = res.data || [];
};
//获取授课教师
const teacherOptions = ref([]);
const getApiTeacherOptionsPost = async () => {
  //const res = await api.apiTeacherOptionsPost({ keyWords: '' });
  const res = await api.apiTeacherTeachersInMyCompaniesPost();
  console.log(res);
  teacherOptions.value = res.data || [];
};
//获取预约重复
const appointmentRepeatTypeOptions = ref([
  { value: "", label: "永不", tag: "", text: "永不" },
]);
const getApiAppointmentRepeatTypeOptionsPost = async () => {
  const res = await SAPI.AppointmentRepeatTypeOptions({ keyWords: "" });
  console.log(res, 123);
  appointmentRepeatTypeOptions.value =
    appointmentRepeatTypeOptions.value.concat(res);
};

//日期选择器
const onChangeDate = (dates, dateStrings) => {
  queryState.value.begin_dateRange = dateStrings[0] ? dateStrings : null;
  queryState.value.time = dates;
};

const onChangeFormDate = (dates, dateStrings) => {
  formState.value.begin_date = dateStrings[0] || "";
  formState.value.end_date = dateStrings[1] || "";
  formState.value.date = dates;
};
const onChangeFormTime = (dates, dateStrings) => {
  formState.value.begin_time = dateStrings[0] || "";
  formState.value.end_time = dateStrings[1] || "";
  formState.value.time = dates;
};

const onChangeAppointmentFormDate = (dates, dateStrings) => {
  formState.value.appointmentdate = dates || "";
  formState.value.appointment_date = dateStrings || "";
};

//获取预约列表分页
const current = ref(1);
const pageSize = ref(10);
const getApiAppointmentPagedListPost = async (type = false) => {
  if (type) {
    current.value = 1;
  }
  const res = await api.apiAppointmentPagedListPost({
    args: {
      current: current.value,
      pageSize: pageSize.value,
      for_school_manager: true,
      name: queryState.value.name,
      appointment_status_idArray:
        queryState.value.appointment_status_idArray != null
          ? [queryState.value.appointment_status_idArray]
          : [],
      begin_dateRange: queryState.value.begin_dateRange,
      laboratory_idArray:
        queryState.value.laboratory_idArray != null
          ? [queryState.value.laboratory_idArray]
          : [],
    },
  });
  tableData.value = res.data?.data || [];
  total.value = res.data?.total || 0;
};

const modal2Visible = ref(false);
const handleAdd = () => {
  // store.setSubTitle("新增客户");
  // router.push("senior-customer-option");
  formState.value = {
    laboratory_id: null,
    teacher_id: null,
    repeat_type_id: "",
    experiment_name: "",
    is_repeat: null,
    date: null,
    time: null,
    skip_holiday: null,
    appointmentdate: null,
  };
  modal2Visible.value = true;

  nextTick(() => {
    formRef.value.resetFields();
  });
};
const formRef = ref();
const handleOk = async (e) => {
  console.log(formState.value);
  formRef.value
    .validate()
    .then(async () => {
      let params = {
        laboratory_id: formState.value.laboratory_id,
        teacher_id: formState.value.teacher_id,
        repeat_type_id: formState.value.repeat_type_id || undefined,
        experiment_name: formState.value.experiment_name,
        is_repeat: formState.value.repeat_type_id ? true : false,
        begin_date: formState.value.begin_date,
        end_date: formState.value.end_date,
        skip_holiday: formState.value.skip_holiday,
        appointment_date: formState.value.appointment_date,
      };
      const res = await api.apiAppointmentCreatePost(params);
      if (res) {
        message.success("创建成功");
        modal2Visible.value = false;
        await getApiAppointmentPagedListPost();
      } else {
        message.error("创建失败");
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};

onMounted(async () => {
  windowWidth.value = window.innerWidth;
  if (windowWidth.value > 768) {
    expand.value = true;
  } else {
    expand.value = false;
  }
  window.addEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
    if (windowWidth.value > 768) {
      expand.value = true;
    } else {
      expand.value = false;
    }
  });
  await getApiLaboratoryOptionsPost();
  await getApiAppointmentStatusOptionsPost();
  await getApiTeacherOptionsPost();
  await getApiAppointmentRepeatTypeOptionsPost();
  await getApiAppointmentPagedListPost(true);
});
onUnmounted(() => {
  window.removeEventListener("resize", () => {});
});

async function onFinish(values) {
  console.log("Success:", values);
  await getApiAppointmentPagedListPost();
}
const tableData = ref([]);

const columns = ref([
  {
    dataIndex: "laboratory_name",
    title: "实验室",
    width: 110,
  },
  {
    dataIndex: "appointment_date",
    title: "日期",
    width: 150,
  },
  {
    dataIndex: "begin_time",
    title: "时间",
    width: 110,
  },
  {
    dataIndex: "teacher_name",
    title: "预约人",
    width: 110,
  },
  {
    dataIndex: "appointment_status_name",
    title: "预约状态",
    width: 110,
  },
  {
    dataIndex: "experiment_name",
    title: "实验",
    width: 110,
  },
  {
    dataIndex: "operation",
    title: "操作",
    width: 160,
    align: "center",
    fixed: "right",
  },
]);

const onChange = (page) => {
  console.log(page);
  current.value = page.current;
  pageSize.value = page.pageSize;
  getData();
};

const total = ref(0);
const pagination = computed(() => ({
  position: ["bottomCenter"],
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  size: "large",
  showTotal: (total) => `共 ${total} 条`,
}));

const handleDelte = async (data) => {
  const res = await api.apiAppointmentDeletePost({
    appointment_id: data.appointment_id,
  });
  if (res) {
    message.success("撤销成功");
    await getApiAppointmentPagedListPost();
  } else {
    message.error("撤销失败");
  }
};
</script>
<style lang="less" scoped>
.list-pages {
  height: 100%;
  padding: 0 16px;
  display: flex;
  flex-direction: column;

  .search-box {
    display: flex;
    align-items: center;
    padding: 18px 0;
    flex-wrap: wrap;
    border-bottom: 1px solid #e5e7eb;

    .search-select {
      width: 120px;
    }

    .line {
      width: 1px;
      height: 16px;
      margin: 0 12px;
      background: #bec4ca;

      @media screen and (max-width: 768px) {
        display: none;
      }
    }

    .search-input-box {
      flex: 1;
      display: flex;
      align-items: center;

      @media screen and (max-width: 768px) {
        width: 100%;
        margin-top: 16px;
        justify-content: space-between;
      }
    }

    .search-input {
      flex: 1;
    }

    .search-btn {
      width: 60px;
      height: 32px;
      background: #2776ff;
      border-radius: 4px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 32px;
    }
  }

  .table-wrapper {
    width: 100%;
    flex: 1;
    overflow: hidden;

    .table-box {
      height: 100%;
    }
  }

  .list-box {
    width: 100%;
    box-sizing: border-box;
    padding-top: 16px;
    overflow: auto;
    display: grid;
    gap: 16px;
    margin: 0 auto;
    grid-template-columns: repeat(auto-fill, minmax(261px, 1fr));
    justify-content: space-between;

    .list-item {
      width: 261px;
      background: #ffffff;
      border: 1px solid #e6ebf1;
      border-radius: 8px;
      box-sizing: border-box;
      padding: 8px;
      margin: auto;
      position: relative;
      cursor: pointer;

      &:hover {
        border: 1px solid #2776ff;
        box-shadow: 12px 12px 12px 0px rgba(39, 118, 255, 0.1);
      }

      .item-collect {
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        width: 32px;
        height: 32px;
        background: rgba(0, 0, 0, 0.4) url(@/assets/icon-collet.png) no-repeat
          center center;
        border-radius: 0 8px 0 12px;

        &.cur {
          background: #ffffff url(@/assets/icon-collet-cur.png) no-repeat center
            center;
          border-radius: 0 8px 0 12px;
        }
      }

      .list-img {
        width: 245px;
        height: 249px;
        background: #f3f3f3;
        border: 1px solid #e6ebf1;
        border-radius: 8px;
        box-sizing: border-box;

        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }

      .list-content {
        padding: 14px 0 6px;
        display: flex;
        flex-direction: column;

        .content-title {
          font-family: PingFangSC-Medium;
          font-weight: 500;
          font-size: 16px;
          color: #31323a;
          margin-bottom: 10px;
          line-height: 24px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .content-col {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .col-user {
            display: flex;
            align-items: center;

            .user-img {
              width: 26px;
              height: 26px;
              border-radius: 50%;
            }

            .user-name {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 12px;
              color: #262626;
              line-height: 16px;
              text-align: left;
              font-style: normal;
            }
          }

          .col-date {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #8c8c8c;
            line-height: 16px;
            text-align: center;
            font-style: normal;
          }
        }
      }
    }
  }

  .pagination-box {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
